package com.qf.java2201.edu.userservice.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.java2201.common.R;
import com.qf.java2201.edu.userservice.pojo.User;
import com.qf.java2201.edu.userservice.service.RoleService;
import com.qf.java2201.edu.userservice.service.UserService;
import com.qf.java2201.edu.userservice.token.TokenService;
import com.qf.java2201.edu.userservice.web.model.LoginUser;
import com.qf.java2201.edu.userservice.web.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @date 2022/5/28
 * @desc
 */
@RestController
@RequestMapping("/userservice/user")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginService loginService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/login")
    @ApiOperation(value= "用户登录")
    public R login(@RequestBody LoginUser loginUser){

        //登录成功  返回 token
        String token = loginService.login(loginUser.getUsername(), loginUser.getPassword());

        return R.ok().data("token",token);
    }

    @GetMapping("/info")
    public R info(String token){

        LoginUser loginUser = tokenService.getLoginUser(token);
        User userInfo = userService.findUserByUserName(loginUser.getUsername());
        Set<String> roleList = roleService.getRolePermsByUserId(userInfo.getUserId());

        return R.ok().data(MapUtil.builder()
                .put("id", userInfo.getUserId())
                .put("name", userInfo.getUsername())
                .put("avatar", userInfo.getPicture())
                .put("roles", roleList)
                .put("introduction", "I am a super administrator").build());

    }




  //---------------------------------------------------------------









    @RequestMapping("/list")
    @ApiOperation(value = "查询所有用户列表")
    public R userList(){
        List<User> list = userService.list();
        return R.ok().data("data",list);
    }


    @PostMapping("/page")
    @ApiOperation(value = "分页查询")
    @Secured({"ROLE_admin"})
    public R getPage(@RequestBody Map<String,Object> params){
        System.out.println(params);

        Page<User> page = userService.queryPage(params);

        return R.ok().data("page",page);
    }

    @GetMapping("/getUserById/{userId}")
    public R getUserById(@PathVariable("userId") Integer userId){
        User user = userService.getById(userId);
        return R.ok().data("user",user);
    }
}
